package edu.gu.hajo.gcl.cmd.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.gu.hajo.gcl.exception.ExecException;
import edu.gu.hajo.gcl.interp.IInterpreter;
import edu.gu.hajo.gcl.script.Script;

public class Procedure extends AbstractCmd {

	private String name;

	private String[] params;

	private Script body;

	Map<String, String> localVars = new HashMap<String, String>();

	public Procedure(List<String> args, IInterpreter interp) {
		super(interp);
		if (args.size() != 3) {
			throw new ExecException("Procedure missing name, params or body");
		}
		name = args.get(0).trim();
		// TODO Needed?
		String s = args.get(1).trim().replaceAll("\\s+", " ");
		params = s.split("[ ]");
		body = new Script(args.get(2));
	}

	public void execute() {
		if (params.length != args.size()) {
			throw new ExecException("Parameters and args mismatch");
		}
		// Must start over!
		body.first();
		
		for (int i = 0; i < params.length; i++) {
			localVars.put(params[i], args.get(i));
		}

		interp.pushCallframe(name, localVars);
		interp.eval(body);
		interp.popCallframe();

		// If stopped int the middel of body
		// (by return)
		body.last();
		interp.setReturn(false);
	}
}
